/*
 * @Copyright (c) 2018 缪聪(mcg-helper@qq.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");  
 * you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *     
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *     
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.
 */

package com.mcgrobot.plugin.schedule;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mcgrobot.common.SpringContextHelper;
import com.mcgrobot.service.STimetaskLogService;

public class TaskUtils {
  public final static Logger log = LoggerFactory.getLogger(TaskUtils.class);
 
  private static STimetaskLogService sTimetaskLogService = (STimetaskLogService) SpringContextHelper.getSpringBean(STimetaskLogService.class);
  /**
   * 通过反射调用scheduleJob中定义的方法
   * 
   * @param scheduleJob
   */
  @SuppressWarnings("unchecked")
  public static void invokMethod(ScheduleJob scheduleJob) {
    Object object = null;
    Class clazz = null;
    boolean flag = true;
    if (StringUtils.isNotBlank(scheduleJob.getSpringBeanName())) {
      object = SpringContextHelper.getSpringBean(scheduleJob.getSpringBeanName());
    } else if (StringUtils.isNotBlank(scheduleJob.getBeanClass())) {
      try {
        clazz = Class.forName(scheduleJob.getBeanClass());
        object = clazz.newInstance();
      } catch (Exception e) {
        flag = false;
        STimetaskLog tlog = new STimetaskLog();
        tlog.setId(UUID.randomUUID().toString());
        tlog.setCreateDate(new Date());
        tlog.setJobId(scheduleJob.getJobId().toString());
        tlog.setReason("未找到"+scheduleJob.getBeanClass()+"对应的class");
        tlog.setState("fail");
        sTimetaskLogService.insertSelective(tlog);
        e.printStackTrace();
      }
 
 
    }
    if (object == null) {
      flag = false;
      log.error("任务名称 = [" + scheduleJob.getJobName() + "]---------------未启动成功，请检查是否配置正确！！！");
      STimetaskLog tlog = new STimetaskLog();
      tlog.setId(UUID.randomUUID().toString());
      tlog.setCreateDate(new Date());
      tlog.setJobId(scheduleJob.getJobId().toString());
      tlog.setReason("未找到"+scheduleJob.getBeanClass()+"对应的class");
      tlog.setState("fail");
      sTimetaskLogService.insertSelective(tlog);
      return;
    }
    clazz = object.getClass();
    Method method = null;
    try {
    	method = clazz.getDeclaredMethod(scheduleJob.getMethodName(), new Class[] { String.class });
    } catch (NoSuchMethodException e) {
      flag = false;
      log.error("任务名称 = [" + scheduleJob.getJobName() + "]---------------未启动成功，方法名设置错误！！！");
      STimetaskLog tlog = new STimetaskLog();
      tlog.setId(UUID.randomUUID().toString());
      tlog.setCreateDate(new Date());
      tlog.setJobId(scheduleJob.getJobId().toString());
      tlog.setReason("未找到"+scheduleJob.getBeanClass()+"类下"+scheduleJob.getMethodName()+"对应的方法");
      tlog.setState("fail");
      sTimetaskLogService.insertSelective(tlog);
    } catch (SecurityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if (method != null) {
      try {
        method.invoke(object, scheduleJob.getJobData());
      } catch (IllegalAccessException e) {
        flag = false;
        STimetaskLog tlog = new STimetaskLog();
        tlog.setId(UUID.randomUUID().toString());
        tlog.setCreateDate(new Date());
        tlog.setJobId(scheduleJob.getJobId().toString());
        tlog.setReason("未找到"+scheduleJob.getBeanClass()+"类下"+scheduleJob.getMethodName()+"对应的方法参数设置错误");
        tlog.setState("fail");
        sTimetaskLogService.insertSelective(tlog);
        e.printStackTrace();
      } catch (IllegalArgumentException e) {
        flag = false;
        STimetaskLog tlog = new STimetaskLog();
        tlog.setId(UUID.randomUUID().toString());
        tlog.setCreateDate(new Date());
        tlog.setJobId(scheduleJob.getJobId().toString());
        tlog.setReason("未找到"+scheduleJob.getBeanClass()+"类下"+scheduleJob.getMethodName()+"对应的方法参数设置错误");
        tlog.setState("fail");
        sTimetaskLogService.insertSelective(tlog);
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        flag = false;
        STimetaskLog tlog = new STimetaskLog();
        tlog.setId(UUID.randomUUID().toString());
        tlog.setCreateDate(new Date());
        tlog.setJobId(scheduleJob.getJobId().toString());
        tlog.setReason("未找到"+scheduleJob.getBeanClass()+"类下"+scheduleJob.getMethodName()+"对应的方法参数设置错误");
        tlog.setState("fail");
        sTimetaskLogService.insertSelective(tlog);
        e.printStackTrace();
      }
    }
    if(flag){
      System.out.println("任务名称 = [" + scheduleJob.getJobName() + "]----------启动成功");
      STimetaskLog tlog = new STimetaskLog();
      tlog.setId(UUID.randomUUID().toString());
      tlog.setCreateDate(new Date());
      tlog.setJobId(scheduleJob.getJobId().toString());
      tlog.setState("success");
      sTimetaskLogService.insertSelective(tlog);
    }
    
  }
}